// pages/login/index.js
// 引入校验插件
import wxValidate from 'wechat-validate'

Page({
  data: {  
    smsCode: '246810',
    base64: '',
    mobile: '15038624355',
    captchaKey: '',
    captchaCode: '',
    redirectUrl: ''
  },

  // 注册校验插件
  behaviors: [wxValidate],

  // 定义校验规则
  rules: {
    mobile: [
      {required: true, message: '请填写手机号码!'},
      {pattern: /^1[3-8]\d{9}$/, message: '请填写正确的手机号码!'}
    ],
    captchaCode: [
      {required: true, message: '请填写图形验证码!'}
    ],
    smsCode: [
      {required: true, message: '请填写短信验证码!'},
      {pattern: /^\d{6}$/, message: '请填写正确的短信验证码!'}
    ]
  },

  onLoad(e) {
    this.getImgSMS()

    // 接收传递过来的路径参数
    // console.log(e.redirectUrl)
    // 将接收到的参数进行全局存储
    this.redirectUrl = e.redirectUrl
  },

  // 左回退
  onClickLeft() {
    wx.switchTab({
      url: '/pages/my/index',
    })
  },

  // 获取图片验证码
  async getImgSMS() {
    // console.log('getImgSMS')
    const {data} = await wx.http.get('/captcha/image')
    // console.log(data.data)
    this.setData({
      base64: data.data.base64,
      captchaKey: data.data.key
    })
  },

  // 获取短信验证码
  async getMsgSMS() {
    const {valid, message} = this.validate('mobile', 'captchaCode')
    if (!valid) return wx.utils.toast(message)
    // console.log('getMsgSMS')
    const {data} = await wx.http.post('/captcha/sendSmsCaptcha', 
    {
      form: {
        captchaCode: this.data.captchaCode, 
        captchaKey: this.data.captchaKey, 
        mobile: this.data.mobile
      }
    }
    )
    console.log(data)
    if (data.status !== 200) return wx.utils.toast('获取短信验证码失败！')
    console.log(data)
  },

  // 点击登录事件，调用登录接口
  async login() {
    const isOk = this.validate()
    if (!isOk) return
    // console.log('login')
    const {data} = await wx.http.post('/passport/login', {
      form: {
        isParty: false,
        mobile: this.data.mobile,
        partyData: {},
        smsCode: this.data.smsCode
      }
    })
    // console.log(data)
    // console.log(data.data.token)
    if (data.status !== 200) return wx.utils.toast('登录失败，请稍后重试！')
    // 调app实例中的存储token的全局方法
    const app = getApp()
    app.setUserToken('token', data.data.token)
    // token存储成功之后，跳转页面
    // 定义路径白名单
    const tabBarPaths = [
      '/pages/my/index',
      '/pages/shopCar/index'
    ]
    if (tabBarPaths.includes(this.redirectUrl)) {
      wx.switchTab({
        url: this.redirectUrl
      })
    } else {
      wx.redirectTo({
        url: this.redirectUrl
      })
    }
  }
})